package cn.ming.wfchat.app.dynamic.activity;

import android.app.Activity;
import android.content.Intent;
import android.text.TextUtils;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.afollestad.materialdialogs.MaterialDialog;
import com.google.gson.Gson;
import com.lqr.imagepicker.ImagePicker;
import com.lqr.imagepicker.bean.ImageItem;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;

import androidx.annotation.Nullable;
import androidx.recyclerview.widget.ItemTouchHelper;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.StaggeredGridLayoutManager;
import butterknife.BindView;
import cn.ming.wfchat.R;
import cn.ming.wfchat.app.AppService;
import cn.ming.wfchat.app.dynamic.bean.ReleaseBean;
import cn.ming.wfchat.app.dynamic.callback.MyCallBack;
import cn.ming.wfchat.app.dynamic.callback.OnRecyclerItemClickListener;
import cn.ming.wfchat.app.main.EventBusBean;
import cn.ming.wfchat.app.main.EventConstant;
import cn.ming.wfchat.app.moment.PostArticleImgAdapter;
import cn.ming.wfchat.app.utils.ImageLoaderUtil;
import cn.ming.wfchat.kit.WfcBaseActivity;
import cn.ming.wfchat.kit.mm.MMPreviewActivity;
import cn.ming.wfchat.kit.mm.MediaEntry;
import cn.ming.wfchat.kit.net.base.StatusResult;
import cn.wildfirechat.remote.ChatManager;
import cn.wildfirechat.remote.OssManager;

/**
 * 发布动态
 */
public class ReleaseDynamicActivity extends WfcBaseActivity {


    @BindView(R.id.editText)
    EditText editText;
    @BindView(R.id.preview_image_content)
    RecyclerView rcvImg;

    public static final String VIDEO_URL = "video_url";
    public static final String IMAGE_URLS = "image_urls";
    @BindView(R.id.tv)
    TextView tv;
    @BindView(R.id.iv_pay)
    ImageView ivPay;
    @BindView(R.id.rl_vdieo)
    RelativeLayout rlVdieo;
    private String videoPath = null;
    private static final int REQUEST_CODE_PICK_IMAGE = 100;
    private static final int REQUEST_CODE_VISIBLE_SCOPE = 102;
    private List<String> imageUrls;
    private MaterialDialog dialog;
    private PostArticleImgAdapter postArticleImgAdapter;
    private ItemTouchHelper itemTouchHelper;
    private String conut;
    private String password;

    @Override
    protected int contentLayout() {
        return R.layout.activity_release_dynamic;
    }

    @Override
    protected void afterViews() {
        setTitle("发布动态");
        init();
    }

    private void init() {
        videoPath = getIntent().getStringExtra(VIDEO_URL);
        imageUrls = getIntent().getStringArrayListExtra(IMAGE_URLS);
        if (!TextUtils.isEmpty(videoPath) || (imageUrls != null && !imageUrls.isEmpty())) {
            if (!TextUtils.isEmpty(videoPath)) {
                rlVdieo.setVisibility(View.VISIBLE);
                rcvImg.setVisibility(View.GONE);
                initVideo();
            } else {
                rlVdieo.setVisibility(View.GONE);
                rcvImg.setVisibility(View.VISIBLE);
                initRcv();
            }

        } else {
            rcvImg.setVisibility(View.GONE);
        }
    }

    /**
     * 初始化视频
     */
    void initVideo() {
        ImageLoaderUtil.displaylocal(ivPay, videoPath);
        ivPay.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                List<MediaEntry> mediaEntries = new ArrayList<>();
                MediaEntry mediaEntry = new MediaEntry();
                mediaEntry.setType(MediaEntry.TYPE_VIDEO);
                mediaEntry.setMediaLocalPath(videoPath);
                mediaEntry.setMediaUrl(videoPath);
                mediaEntry.setThumbnailUrl(videoPath);
                mediaEntries.add(mediaEntry);
                MMPreviewActivity.startActivity(ReleaseDynamicActivity.this, mediaEntries, 1);
            }
        });
        imageUrls = new ArrayList<>();
        imageUrls.add(videoPath);
    }

    @Override
    protected int menu() {
        return R.menu.release;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        switch (item.getItemId()) {

            case R.id.direct_release:
                if (TextUtils.isEmpty(editText.getText().toString().trim())) {
                    ChatManager.showToast("发布内容不能为空 ");
                } else {
                    conut = null;
                    DirectRelease();
                }
                break;
            case R.id.more_people:
                if (TextUtils.isEmpty(editText.getText().toString().trim())) {
                    ChatManager.showToast("发布内容不能为空 ");
                } else {
                    Intent intent = new Intent(ReleaseDynamicActivity.this, SelectNumberActivity.class);
                    startActivityForResult(intent, REQUEST_CODE_VISIBLE_SCOPE);
                }
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    void DirectRelease() {
        dialog = new MaterialDialog.Builder(this)
                .content("发布中...")
                .progress(true, 100)
                .cancelable(false)
                .build();
        dialog.show();
        ReleaseBean releaseBean = new ReleaseBean();
        releaseBean.setContent(editText.getText().toString().trim());
        if (imageUrls != null && imageUrls.size() > 0) {
            List<ReleaseBean.ResourcesBean> resourcesBeans = new ArrayList<>();

            for (int i = 0; i < imageUrls.size(); i++) {
                OssManager.getInstance().upload(ReleaseDynamicActivity.this, i, imageUrls.get(i), new OssManager.OnUploadListener() {
                    @Override
                    public void onProgress(int position, long currentSize, long totalSize) {
//                        runOnUiThread(new Runnable() {
//                            @Override
//                            public void run() {
//                                ChatManager.showToast("正在上传第" + position + "张" + currentSize);
//                            }
//                        });

                    }

                    @Override
                    public void onSuccess(int position, String uploadPath, String imageUrl) {
                        ReleaseBean.ResourcesBean resourcesBean = new ReleaseBean.ResourcesBean(imageUrl, videoPath == null ? "IMG" : "VIDEO");
                        resourcesBeans.add(resourcesBean);
                        releaseBean.setResources(resourcesBeans);
                        if (resourcesBeans.size() == imageUrls.size()) {
                            releaseDynamics(releaseBean);
                        }
                    }

                    @Override
                    public void onFailure(int position) {
                        dialog.dismiss();
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                ChatManager.showToast("上传失败");
                            }
                        });
                    }
                }, videoPath == null ? 1 : 2);
            }

        } else {
            releaseDynamics(releaseBean);
        }


    }

    void releaseDynamics(ReleaseBean releaseBean) {
        if (!TextUtils.isEmpty(password)) {
            releaseBean.setPayPassword(password);
        }
        if (!TextUtils.isEmpty(conut)) {
            releaseBean.setCount(conut);
        }
        String connect = new Gson().toJson(releaseBean);
        AppService.Instance().releaseDynamics(connect, new AppService.ReleaseDynamicsCallback() {
            @Override
            public void onUiSuccess(StatusResult assetsBean) {
                dialog.dismiss();
                ChatManager.showToast("发布成功 ");
                EventBus.getDefault().post(new EventBusBean(EventConstant.UPDATEMOMENTS));
                finish();
            }

            @Override
            public void onUiFailure(int code, String msg) {
                dialog.dismiss();
                ChatManager.showToast("请求失败 " + code + msg);
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        if (resultCode != Activity.RESULT_OK) {
            return;
        }
        if (requestCode == REQUEST_CODE_PICK_IMAGE) {
            if (data != null) {
                ArrayList<ImageItem> images = (ArrayList<ImageItem>) data.getSerializableExtra(ImagePicker.EXTRA_RESULT_ITEMS);
                List<String> imageUrls = postArticleImgAdapter.getImageUrls();
                for (ImageItem imageItem : images) {
                    imageUrls.add(imageItem.path);
                }

                postArticleImgAdapter.setmDatas(imageUrls, false);
            }
        } else if (requestCode == REQUEST_CODE_VISIBLE_SCOPE) {
            if (data != null) {
                password = data.getStringExtra("password");
                conut = data.getStringExtra("conut");
                DirectRelease();
            }
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    private void initRcv() {
        postArticleImgAdapter = new PostArticleImgAdapter(ReleaseDynamicActivity.this, imageUrls);
        rcvImg.setLayoutManager(new StaggeredGridLayoutManager(3, StaggeredGridLayoutManager.VERTICAL));
        rcvImg.setAdapter(postArticleImgAdapter);
        MyCallBack myCallBack = new MyCallBack(postArticleImgAdapter, imageUrls, imageUrls);
        itemTouchHelper = new ItemTouchHelper(myCallBack);
        itemTouchHelper.attachToRecyclerView(rcvImg);//绑定RecyclerView

        //事件监听
        rcvImg.addOnItemTouchListener(new OnRecyclerItemClickListener(rcvImg) {

            @Override
            public void onItemClick(RecyclerView.ViewHolder vh) {
                if (vh.getAdapterPosition() < postArticleImgAdapter.getImageUrls().size()) {
                    String path = postArticleImgAdapter.getImageUrls().get(vh.getAdapterPosition());

                    // preview image
                    if (path.endsWith("mp4")) {
                        List<MediaEntry> mediaEntries = new ArrayList<>();
                        MediaEntry mediaEntry = new MediaEntry();
                        mediaEntry.setType(MediaEntry.TYPE_VIDEO);
                        mediaEntry.setMediaLocalPath(path);
                        mediaEntry.setMediaUrl(path);
                        mediaEntry.setThumbnailUrl(path);
                        mediaEntries.add(mediaEntry);
                        MMPreviewActivity.startActivity(ReleaseDynamicActivity.this, mediaEntries, vh.getAdapterPosition());
                    } else {
                        List<MediaEntry> mediaEntries = new ArrayList<>();
                        for (String src : postArticleImgAdapter.getImageUrls()) {
                            MediaEntry mediaEntry = new MediaEntry();
                            mediaEntry.setType(MediaEntry.TYPE_IMAGE);
                            mediaEntry.setMediaUrl(src);
                            mediaEntry.setMediaLocalPath(src);
                            mediaEntries.add(mediaEntry);
                        }
                        MMPreviewActivity.startActivity(ReleaseDynamicActivity.this, mediaEntries, vh.getAdapterPosition());
                    }
                } else {
                    // add more image
                    int count = 9 - postArticleImgAdapter.getImageUrls().size();
                    Intent intent = ImagePicker.picker().showCamera(true).enableMultiMode(count).buildPickIntent(ReleaseDynamicActivity.this);
                    startActivityForResult(intent, REQUEST_CODE_PICK_IMAGE);
                }
            }

            @Override
            public void onItemLongClick(RecyclerView.ViewHolder vh) {
                //如果item不是最后一个，则执行拖拽
                if (vh.getLayoutPosition() != imageUrls.size() - 1) {
                    itemTouchHelper.startDrag(vh);
                }
            }
        });

        myCallBack.setDragListener(new MyCallBack.DragListener() {
            @Override
            public void deleteState(boolean delete) {
                if (delete) {
                    tv.setBackgroundResource(R.color.holo_red_dark);
                    tv.setText(getResources().getString(R.string.post_delete_tv_s));
                } else {
                    tv.setText(getResources().getString(R.string.post_delete_tv_d));
                    tv.setBackgroundResource(R.color.holo_red_light);
                }
            }

            @Override
            public void dragState(boolean start) {
                if (start) {
                    tv.setVisibility(View.VISIBLE);
                } else {
                    tv.setVisibility(View.GONE);
                }
            }

            @Override
            public void clearView() {

            }
        });
    }


}
